package com.zougen202301180355.restaurant.controller;

import com.zougen202301180355.restaurant.pojo.MenuItem;
import com.zougen202301180355.restaurant.service.MenuItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 邹根
 * 菜单管理控制器
 */
@Controller
@RequestMapping("/menuitems")
public class MenuItemsController {

    @Autowired
    private MenuItemsService menuItemsService;

    /**
     * 显示菜品列表
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<MenuItem> menuItems = menuItemsService.getAllMenuItems();
        model.addAttribute("menuItems", menuItems);
        return "menuitems/list";
    }

    /**
     * 显示添加菜品页面
     */
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("menuItem", new MenuItem());
        return "menuitems/add";
    }

    /**
     * 处理添加菜品请求
     */
    @PostMapping("/add")
    public String addMenuItem(@ModelAttribute MenuItem menuItem) {
        menuItemsService.addMenuItem(menuItem);
        return "redirect:/menuitems/list";
    }

    /**
     * 显示编辑菜品页面
     */
    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable("id") Integer id, Model model) {
        MenuItem menuItem = menuItemsService.getMenuItemById(id);
        model.addAttribute("menuItem", menuItem);
        return "menuitems/edit";
    }

    /**
     * 处理编辑菜品请求
     */
    @PostMapping("/edit")
    public String editMenuItem(@ModelAttribute MenuItem menuItem) {
        menuItemsService.updateMenuItem(menuItem);
        return "redirect:/menuitems/list";
    }

    /**
     * 删除菜品
     */
    @GetMapping("/delete/{id}")
    public String deleteMenuItem(@PathVariable("id") Integer id, Model model) {
        try {
            menuItemsService.deleteMenuItem(id);
            return "redirect:/menuitems/list";
        } catch (Exception e) {
            // 外键约束异常，该菜品被订单详情引用
            if (e.getMessage().contains("foreign key constraint") || 
                e.getCause() != null && e.getCause().getMessage().contains("foreign key constraint")) {
                model.addAttribute("error", "无法删除：该菜品已被订单引用，请先删除相关订单详情。");
            } else {
                model.addAttribute("error", "删除失败：" + e.getMessage());
            }
            // 重新加载菜品列表
            model.addAttribute("menuItems", menuItemsService.getAllMenuItems());
            return "menuitems/list";
        }
    }
}
